package org.example.buysystem.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.buysystem.common.Result;
import org.example.buysystem.constants.Constants;
import org.example.buysystem.constants.RedisConstants;
import org.example.buysystem.entity.LoginForm;
import org.example.buysystem.entity.User;
import org.example.buysystem.entity.dto.UserDto;
import org.example.buysystem.exception.ServiceException;
import org.example.buysystem.mapper.UserMapper;
import org.example.buysystem.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {


    @Resource
    RedisTemplate<String, User> redisTemplate;

    @Autowired
    private UserMapper userMapper;
    public UserDto login(LoginForm loginForm) {
//        User user=userMapper.selectloginuser(loginForm);

        QueryWrapper<User> queryWrapper=new QueryWrapper<>();

        queryWrapper.eq("username",loginForm.getUsername()).eq("password",loginForm.getPassword());

        User user=getOne(queryWrapper);

        if(user==null){
            throw new ServiceException(Constants.CODE_403,"用户名或密码错误");
        }

        String token= TokenUtils.genToken(user.getId().toString(),user.getPassword());

        redisTemplate.opsForValue().set(RedisConstants.USER_TOKEN_KEY+token,user);

        //jwt不设置过期时间，只设置redis过期时间
        redisTemplate.expire(RedisConstants.USER_TOKEN_KEY+token,RedisConstants.USER_TOKEN_TTL, TimeUnit.MINUTES);

        UserDto userDto= BeanUtil.copyProperties(user,UserDto.class);

        userDto.setToken(token);
        user.setRole("user");
        return userDto;


    }

    public User register(LoginForm loginForm) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",loginForm.getUsername());
        User user=getOne(queryWrapper);
        if(user!=null) {//用户名重复
            throw new ServiceException(Constants.CODE_403, "用户名重复");
        }else {
            user = new User();
            BeanUtil.copyProperties(loginForm,user);
            user.setNickname("新用户");
            user.setRole("user");
            save(user);
            return user;
        }
    }

    public User getUsername(String username) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return getOne(queryWrapper);
    }

    public void resetPassword(String id, String newPassword) {
        User user = getById(id);
        if(user==null){
            return;
        }
        user.setPassword(newPassword);
        this.updateById(user);

    }

    public Result saveUpdate(User user) {
        if(user.getId()!=null){
            User old=this.baseMapper.selectById(user.getId());
            old.setNickname(ObjectUtils.isEmpty(user.getNickname())?old.getNickname():user.getNickname());
            old.setAvatarUrl(ObjectUtils.isEmpty(user.getAvatarUrl())?old.getAvatarUrl():user.getAvatarUrl());
            old.setRole(ObjectUtils.isEmpty(user.getRole())?old.getRole():user.getRole());
            old.setPhone(ObjectUtils.isEmpty(user.getPhone())?old.getPhone():user.getPhone());
            old.setEmail(ObjectUtils.isEmpty(user.getEmail())?old.getEmail():user.getEmail());
            old.setAddress(ObjectUtils.isEmpty(user.getAddress())?old.getAddress():user.getAddress());

            super.updateById(old);
            return Result.success("修改成功");
        }else{
            if(!ObjectUtils.isEmpty(this.getOne(user.getUsername()))){
                return Result.error("400", "用户名已存在");
            }
            user.setPassword(user.getPassword());
            super.save(user);
            return Result.success("新增成功");

        }

    }

    private User getOne(String username){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return getOne(queryWrapper);
    }
}
